/**
 * 工具函数集合
 */

// 验证年级范围
export function isValidGrade(grade) {
  const g = parseInt(grade);
  return !isNaN(g) && g >= 1 && g <= 9;
}

// 验证班级范围
export function isValidClass(classNum) {
  const c = parseInt(classNum);
  return !isNaN(c) && c >= 1 && c <= 5;
}

// 验证分类范围
export function isValidCategory(category) {
  const cat = parseInt(category);
  return !isNaN(cat) && cat >= 1 && cat <= 6;
}

// 验证状态值
export function isValidStatus(status) {
  const s = parseInt(status);
  return [0, 1, 2].includes(s);
}

// 获取年级显示文本
export function getGradeText(grade) {
  const gradeMap = {
    1: '一年级',
    2: '二年级',
    3: '三年级',
    4: '四年级',
    5: '五年级',
    6: '六年级',
    7: '七年级',
    8: '八年级',
    9: '九年级'
  };
  return gradeMap[grade] || '未知年级';
}

// 获取班级显示文本
export function getClassText(classNum) {
  return `${classNum}班`;
}

// 获取分类显示文本
export function getCategoryText(category) {
  const categoryMap = {
    1: '校园故事',
    2: '学习心得',
    3: '科技创新',
    4: '艺术文化',
    5: '体育活动',
    6: '其他'
  };
  return categoryMap[category] || '其他';
}

// 获取状态显示文本
export function getStatusText(status) {
  const statusMap = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  };
  return statusMap[status] || '未知状态';
}

// 格式化时间戳
export function formatDateTime(timestamp) {
  if (!timestamp) return '未知时间';
  
  const date = new Date(timestamp);
  if (isNaN(date.getTime())) return '无效时间';
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 清理和验证字符串输入
export function sanitizeString(input, maxLength = 1000) {
  if (typeof input !== 'string') return '';
  
  // 去除首尾空白
  const trimmed = input.trim();
  
  // 限制长度
  if (trimmed.length > maxLength) {
    return trimmed.substring(0, maxLength);
  }
  
  return trimmed;
}

// 生成随机ID
export function generateId() {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// 构建分页参数
export function buildPagination(page, limit, total) {
  const pageNum = parseInt(page) || 1;
  const limitNum = parseInt(limit) || 20;
  const totalNum = parseInt(total) || 0;
  
  const safePage = Math.max(1, pageNum);
  const safeLimit = Math.max(1, Math.min(100, limitNum));
  const totalPages = Math.ceil(totalNum / safeLimit);
  
  return {
    page: safePage,
    limit: safeLimit,
    total: totalNum,
    totalPages,
    hasNext: safePage < totalPages,
    hasPrev: safePage > 1
  };
}

// 创建标准的API响应格式
export function createApiResponse(success, data = null, error = null, statusCode = 200) {
  const response = {
    success
  };
  
  if (data !== null) {
    response.data = data;
  }
  
  if (error !== null) {
    response.error = error;
  }
  
  return {
    json: response,
    statusCode
  };
}

// 从请求中提取Cookie值
export function getCookieValue(request, cookieName) {
  const cookie = request.headers.get('Cookie') || '';
  const match = cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));
  return match ? match[2] : null;
}

// 构建安全的Cookie字符串
export function buildSecureCookie(name, value, maxAge = 3600) {
  return `${name}=${value}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${maxAge}`;
}

// 清除Cookie
export function clearCookie(name) {
  return `${name}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`;
}